package com.ruoyi.framework.web.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pay.domain.PayCoinUserForm;
import com.ruoyi.pay.domain.PayOrder;
import com.ruoyi.pay.domain.vo.PayCoinVO;
import com.ruoyi.pay.domain.vo.PayOrderVO;
import com.ruoyi.pay.service.IPayCoinUserService;
import com.ruoyi.pay.service.IPayOrderService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wq.domain.WqActivity;
import com.ruoyi.wq.domain.WqActivityUser;
import com.ruoyi.wq.domain.WqTuan;
import com.ruoyi.wq.domain.WqTuanHome;
import com.ruoyi.wq.domain.WqUserTuan;
import com.ruoyi.wq.service.IWqActivityService;
import com.ruoyi.wq.service.IWqActivityUserService;
import com.ruoyi.wq.service.IWqTuanHomeService;
import com.ruoyi.wq.service.IWqTuanService;
import com.ruoyi.wq.service.IWqUserTuanService;
import com.ruoyi.wx.domain.WxMaMsgForm;
import com.ruoyi.wx.domain.WxMpMsgForm;
import com.ruoyi.wx.domain.WxPayOrderNotifyInfo;
import com.ruoyi.wx.domain.WxPayReturnInfo;
import com.ruoyi.wx.service.WxMaPayService;
import com.ruoyi.wx.service.WxMsgService;

import cn.hutool.core.date.DateUtil;

@Component
public class OrderService {
	
	@Autowired
    private WxMaPayService wxMaPayService;
	
	@Autowired
	private IPayOrderService payOrderService;
	
	@Autowired
	private IWqActivityUserService wqActivityUserService;
	
	@Autowired
	private IWqActivityService wqActivityService;
	
	@Autowired
	private IWqTuanService wqTuanService;
	
	@Autowired
	private IWqTuanHomeService wqTuanHomeService;
	
	@Autowired
	private IWqUserTuanService wqUserTuanService;
	
	@Autowired
    private IPayCoinUserService payCoinUserService;
	
	@Autowired
	private ISysUserService sysUserService;
	
	@Autowired
	private TuanServcie tuanServcie;
	
	@Autowired
    private CoinUserService coinUserService;
	
	@Autowired
    private WxMsgService wxMsgService;
	
	public WxPayReturnInfo payActivityNum(PayCoinVO payCoin) {
		if(StringUtils.isBlank(payCoin.getSourceId())){
			throw new ServiceException("活动不能为空");
		}
		WqActivity activity = wqActivityService.getById(payCoin.getSourceId());
		if(!"0".equals(activity.getActivityStatus())){
			throw new ServiceException("报名已结束");
		}
		QueryWrapper<WqActivityUser> qw = new QueryWrapper<>();
		WqActivityUser entity = new WqActivityUser();
    	entity.setActivityId(payCoin.getSourceId());
    	entity.setUserId(SecurityUtils.getUserId());
    	qw.setEntity(entity);
    	WqActivityUser activityUser = wqActivityUserService.getOne(qw);
    	if(activityUser != null){
    		if("1".equals(activityUser.getStatus())){
    			throw new ServiceException("已报名成功");
    		}else{
    			// 锁定1分钟
    			Date now = new Date();
    			Date payTime = DateUtil.offsetMinute(now, 1);
    			activityUser.setPayTime(payTime);
    			wqActivityUserService.updateById(activityUser);
    		}
    	}
    	
		PayOrderVO payOrder = new PayOrderVO();
		payOrder.setAppId(payCoin.getAppId());
		payOrder.setAmount(activity.getPayPrice());
		payOrder.setBody("活动订金");
		payOrder.setSourceId(payCoin.getSourceId());
		return payOrderService.createActivityPayOrder(payOrder);
	}

	public String updatePayActivityOrder(String xmlData) {
		WxPayOrderNotifyInfo notify = wxMaPayService.notifyOrder(xmlData);
		String tradeNo = notify.getTradeNo();
		QueryWrapper<PayOrder> queryWrapper = new QueryWrapper<>();
		PayOrder entity = new PayOrder();
		entity.setTradeNo(tradeNo);
		queryWrapper.setEntity(entity);
		PayOrder payOrder = payOrderService.getOne(queryWrapper);
		if(payOrder == null){
			return notify.getNotifyResponse();
		}else{
			if("0".equals(payOrder.getStatus())){
				payOrder.setUpdateTime(DateUtils.getNowDate());
				payOrder.setStatus("1");
				payOrderService.updateById(payOrder);
				
				// 支付成功，更新报名状态
				wqActivityUserService.updateActivityUser(payOrder.getSourceId(), Long.valueOf(payOrder.getUserId()));
				WqActivity activity = wqActivityService.getById(payOrder.getSourceId());
				if(activity != null){
					// 判断人是否够了
					QueryWrapper<WqActivityUser> qw = new QueryWrapper<>();
					WqActivityUser au = new WqActivityUser();
					au.setActivityId(payOrder.getSourceId());
					au.setStatus("1");
					qw.setEntity(au);
					int joinNum = wqActivityUserService.count(qw);
					
					activity.setStatus("1");
					activity.setJoinNum(Long.valueOf(joinNum));
					if(joinNum >= activity.getUserNum()){
						activity.setActivityStatus("1");
						// 给队伍的人发送组队成功通知
						List<SysUser> userList = wqActivityUserService.getUserListByActivityId(activity.getId());
						for(SysUser user : userList){
							WxMaMsgForm form = new WxMaMsgForm();
	            			form.setAppId(user.getAppId());
	            			form.setOpenId(user.getOpenId());
	    					Map<String,String> map = new HashMap<>();
	    					map.put("phrase1", "派对组队成功通知");
	    					map.put("date2", DateUtil.now());
	    					map.put("name3", "派对通知");
	    					map.put("thing4", "您报名的派对已组队成功，请尽快联系队长");
	    					form.setDataMap(map);
	    					form.setPage("pages/game/index?my=true&back=true&id="+activity.getId());
	    					boolean send = wxMsgService.sendSubscribeMsg(form);
	    					if(!send){
	    						WxMpMsgForm msgForm = new WxMpMsgForm();
				        		msgForm.setWxId(user.getWxId());
				        		msgForm.setAppId(user.getAppId());
				        		msgForm.setOpenId(user.getWxOpenId());
				        		Map<String,String> dataMap = new HashMap<>();
				        		dataMap.put("first", "您好，您收到一条私信回复");
				        		dataMap.put("keyword1", "派对组队成功通知");
				        		dataMap.put("keyword2", DateUtil.now());
				        		dataMap.put("keyword3", "您报名的派对已组队成功，请尽快联系队长");
				        		dataMap.put("remark", "本条信息是站内信通知，祝您早日脱单！点击查看详情");
				        		msgForm.setDataMap(dataMap);
				        		msgForm.setPage("pages/game/index?my=true&back=true&id="+activity.getId());
				        		wxMsgService.sendTemplateMsg(msgForm);
	    					}
						}
					}else{
						// 给队伍的人发送加入组队通知
						List<SysUser> userList = wqActivityUserService.getUserListByActivityId(activity.getId());
						for(SysUser user : userList){
							if(!user.getUserId().equals(Long.valueOf(payOrder.getUserId()))){
								WxMpMsgForm msgForm = new WxMpMsgForm();
				        		msgForm.setWxId(user.getWxId());
				        		msgForm.setAppId(user.getAppId());
				        		msgForm.setOpenId(user.getWxOpenId());
				        		Map<String,String> dataMap = new HashMap<>();
				        		dataMap.put("first", "您好，您收到一条私信回复");
				        		dataMap.put("keyword1", "成员加入派对通知");
				        		dataMap.put("keyword2", DateUtil.now());
				        		dataMap.put("keyword3", "您好，有新的成员加入您的派对");
				        		dataMap.put("remark", "本条信息是站内信通知，祝您早日脱单！点击查看详情");
				        		msgForm.setDataMap(dataMap);
				        		msgForm.setPage("pages/game/index?my=true&back=true&id="+activity.getId());
				        		wxMsgService.sendTemplateMsg(msgForm);
							}
						}
					}
					wqActivityService.updateById(activity);
				}
			}
		}
		return notify.getNotifyResponse();
	}

	public void payCoin(PayCoinVO payCoin) {
		if(payCoin.getCoinNum() == null || payCoin.getCoinNum() < 1){
			return;
		}
		Integer amount = payCoinUserService.getAmount();
		if(payCoin.getCoinNum() > amount){
			throw new ServiceException("趣币不足");
		}
		PayCoinUserForm payCoinUserForm = new PayCoinUserForm();
		payCoinUserForm.setUserId(SecurityUtils.getUserId());
		payCoinUserForm.setCoinNum(payCoin.getCoinNum());
		payCoinUserForm.setCoinType("1");
		payCoinUserForm.setRemark("到店消费");
		payCoinUserService.savePayCoinUser(payCoinUserForm);
	}

	public WxPayReturnInfo payTuanNum(PayCoinVO payCoin) {
		if(StringUtils.isBlank(payCoin.getSourceId())){
			throw new ServiceException("拼团不能为空");
		}
		WqTuanHome tuanHome = wqTuanHomeService.getById(payCoin.getSourceId());
		if("2".equals(tuanHome.getStatus())){
			throw new ServiceException("拼团已结束");
		}
		QueryWrapper<WqUserTuan> qw = new QueryWrapper<>();
		WqUserTuan entity = new WqUserTuan();
    	entity.setTuanHomeId(payCoin.getSourceId());
    	entity.setUserId(SecurityUtils.getUserId());
    	qw.setEntity(entity);
    	WqUserTuan userTuan = wqUserTuanService.getOne(qw);
    	if(userTuan != null){
    		if("1".equals(userTuan.getStatus())){
    			throw new ServiceException("已加入成功");
    		}
    	}else{
    		SysUser user = sysUserService.getById(SecurityUtils.getUserId());
    		userTuan = new WqUserTuan();
    		userTuan.setUserId(user.getUserId());
    		userTuan.setAvatar(user.getAvatar());
    		userTuan.setSex(user.getSex());
    		userTuan.setNickName(user.getNickName());
    		userTuan.setTuanHomeId(payCoin.getSourceId());
    		wqUserTuanService.saveOrUpdate(userTuan);
    	}
    	
		PayOrderVO payOrder = new PayOrderVO();
		payOrder.setAppId(payCoin.getAppId());
		payOrder.setAmount(tuanHome.getPayPrice());
		payOrder.setBody("会员充值");
		payOrder.setSourceId(payCoin.getSourceId());
		return payOrderService.createTuanPayOrder(payOrder);
	}

	public String updatePayTuanOrder(String xmlData) {
		WxPayOrderNotifyInfo notify = wxMaPayService.notifyOrder(xmlData);
		String tradeNo = notify.getTradeNo();
		QueryWrapper<PayOrder> queryWrapper = new QueryWrapper<>();
		PayOrder entity = new PayOrder();
		entity.setTradeNo(tradeNo);
		queryWrapper.setEntity(entity);
		PayOrder payOrder = payOrderService.getOne(queryWrapper);
		if(payOrder == null){
			return notify.getNotifyResponse();
		}else{
			if("0".equals(payOrder.getStatus())){
				payOrder.setUpdateTime(DateUtils.getNowDate());
				payOrder.setStatus("1");
				payOrderService.updateById(payOrder);
				
				// 支付成功，更新报名状态
				tuanServcie.updateTuanUser(payOrder.getSourceId(), Long.valueOf(payOrder.getUserId()));
				
				WqTuanHome tuanHome = wqTuanHomeService.getById(payOrder.getSourceId());
				if(tuanHome != null){
					// 判断人是否够了
					QueryWrapper<WqUserTuan> qw = new QueryWrapper<>();
					WqUserTuan ut = new WqUserTuan();
					ut.setTuanHomeId(payOrder.getSourceId());
					ut.setStatus("1");
					qw.setEntity(ut);
					int payNum = wqUserTuanService.count(qw);
					
					tuanHome.setStatus("1");
					tuanHome.setPayNum(Long.valueOf(payNum));
					if(payNum >= tuanHome.getUserNum()){
						tuanHome.setStatus("2");
						// 给队伍的人发送组队成功通知
						List<SysUser> userList = wqUserTuanService.getUserListByTuanHomeId(tuanHome.getId());
						for(SysUser user : userList){
							if("0".equals(tuanHome.getTuanType())){
								// 充值趣豆
								PayCoinUserForm payCoinUserForm = new PayCoinUserForm();
						    	payCoinUserForm.setCoinNum(tuanHome.getTuanCoin());
						    	payCoinUserForm.setCoinType("0");
						    	payCoinUserForm.setRemark("拼团成功奖励");
						    	payCoinUserForm.setUserId(user.getUserId());
						    	payCoinUserForm.setIsPay("1");
						    	coinUserService.savePayCoinUser(payCoinUserForm);
							}else{
								// 更新用户会员
								SysUser sysUser = sysUserService.getById(user.getUserId());
								Date vipStartTime = new Date();
								Date vipEndTime = DateUtil.offsetDay(vipStartTime, tuanHome.getBuyCoin());
								if(sysUser.getVipEndTime() != null){
									if(sysUser.getVipEndTime().compareTo(vipStartTime) > 0){
										vipEndTime = DateUtil.offsetDay(sysUser.getVipEndTime(), tuanHome.getTuanCoin());
									}
								}
								sysUser.setVipStartTime(vipStartTime);
								sysUser.setVipEndTime(vipEndTime);
								sysUserService.updateById(sysUser);
							}
							
							WxMpMsgForm msgForm = new WxMpMsgForm();
			        		msgForm.setWxId(user.getWxId());
			        		msgForm.setAppId(user.getAppId());
			        		msgForm.setOpenId(user.getWxOpenId());
			        		Map<String,String> dataMap = new HashMap<>();
			        		dataMap.put("first", "您好，您收到一条私信回复");
			        		dataMap.put("keyword1", "拼团成功通知");
			        		dataMap.put("keyword2", DateUtil.now());
			        		dataMap.put("keyword3", "您参加的拼团已拼团成功，奖励已到账");
			        		dataMap.put("remark", "本条信息是站内信通知，祝您早日脱单！点击查看详情");
			        		msgForm.setDataMap(dataMap);
			        		msgForm.setPage("pages/index?tuan=true&tuanHomeId="+tuanHome.getId());
			        		wxMsgService.sendTemplateMsg(msgForm);
						}
					}else{
						// 给队伍的人发送加入组队通知
						List<SysUser> userList = wqUserTuanService.getUserListByTuanHomeId(tuanHome.getId());
						for(SysUser user : userList){
							if(!user.getUserId().equals(Long.valueOf(payOrder.getUserId()))){
								WxMpMsgForm msgForm = new WxMpMsgForm();
				        		msgForm.setWxId(user.getWxId());
				        		msgForm.setAppId(user.getAppId());
				        		msgForm.setOpenId(user.getWxOpenId());
				        		Map<String,String> dataMap = new HashMap<>();
				        		dataMap.put("first", "您好，您收到一条私信回复");
				        		dataMap.put("keyword1", "新加入拼团通知");
				        		dataMap.put("keyword2", DateUtil.now());
				        		dataMap.put("keyword3", "您参加的拼团有新的用户加入拼团");
				        		dataMap.put("remark", "本条信息是站内信通知，祝您早日脱单！点击查看详情");
				        		msgForm.setDataMap(dataMap);
				        		msgForm.setPage("pages/index?tuan=true&tuanHomeId="+tuanHome.getId());
				        		wxMsgService.sendTemplateMsg(msgForm);
							}
						}
					}
					wqTuanHomeService.updateById(tuanHome);
					
					// 更新已拼人数
					WqTuan tuan = wqTuanService.getById(tuanHome.getTuanId());
					Integer tuanNum = wqTuanHomeService.getTuanHomeNumByTuanId(tuanHome.getTuanId());
					tuan.setTuanNum(tuanNum);
					wqTuanService.updateById(tuan);
				}
			}
		}
		return notify.getNotifyResponse();
	}
	
}
